<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>购物车</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
      integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu"
      crossorigin="anonymous"
    />

    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
      integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ"
      crossorigin="anonymous"
    />

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
      integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
      crossorigin="anonymous"
    ></script>
  </head>
  <style>
    .table {
      width: 700px;
      margin: auto;
    }

    th {
      text-align: center;
    }

    td {
      text-align: center;
    }
  </style>

  <body>
    <button
      type="button"
      class="btn btn-primary"
      data-toggle="modal"
      data-target="#exampleModal"
      data-whatever="@mdo"
    >
      添加商品
    </button>

    <div id="box">
      <div
        class="modal fade"
        id="exampleModal"
        tabindex="-1"
        role="dialog"
        aria-labelledby="exampleModalLabel"
      >
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
              <h4 class="modal-title" id="exampleModalLabel">New message</h4>
            </div>
            <div class="modal-body">
              <form>
                <div class="form-group">
                  <label for="recipient-name" class="control-label"
                    >商品名称:</label
                  >
                  <input type="text" class="form-control" id="recipient-name" />
                </div>
                <div class="form-group">
                  <label for="recipient-name" class="control-label"
                    >商品价格:</label
                  >
                  <input type="text" class="form-control" id="recipient-name" />
                </div>
                <div class="form-group">
                  <label for="recipient-name" class="control-label"
                    >库存:</label
                  >
                  <input type="text" class="form-control" id="recipient-name" />
                </div>
                <!-- <div class="form-group">
                                <label for="recipient-name" class="control-label">添加时间:</label>
                                <input type="text" class="form-control" id="recipient-name">
                            </div> -->
              </form>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-default"
                data-dismiss="modal"
              >
                关闭
              </button>
              <button
                type="button"
                class="btn btn-primary"
                data-dismiss="modal"
                id="btn"
              >
                添加
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <hr />
    <table class="table">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>库存</th>
          <th>添加时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="tbod"></tbody>
    </table>

    <table class="table" style="margin-top: 20px">
      <thead>
        <tr>
          <th><input type="checkbox" id="" /></th>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>数量</th>
          <th>金额</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="tbo"></tbody>
    </table>
  </body>
  <script>
    $(function () {
      render()
    })

    $('#btn').click(function () {
      var shi = getNowTime()
      var arr = {
        商品名称: $('input').eq(0).val(),
        商品价格: $('input').eq(1).val(),
        库存: $('input').eq(2).val(),
        时间: shi,
      }
      setLocal(arr)
      render()
    })

    function delet() {
      del()
      render()
    }

    function gou(obj) {
      var goods = $(obj).parent().siblings()
      var goodsName = $(goods[0]).html(),
        price = $(goods[1]).html()
      if ($(goods[2]).html() == 0) {
        alert(`${goodsName}已售尽`)
        return
      } else {
        $(goods[2]).html($(goods[2]).html() - 1)
      }
      var tdObj = $(`#tbo td:contains("${goodsName}")`)

      if (tdObj.length > 0) {
        var spanObj = tdObj.next().next().children('span')
        spanObj.html(+spanObj.html() + 1)
        tdObj
          .next()
          .next()
          .next()
          .html(price * +spanObj.html())
      } else {
        var htmlTr = `<tr>
                            <td><input type="checkbox" id="inp"></td>
                            <td>${goodsName}</td>
                            <td>${price}</td>
                            <td><button class='jia' name='${goodsName}'>+</button><span>1</span><button name='${goodsName}' class='jian'>-</button></td>
                            <td>${price}</td>
                            <td><button style="height: 30px;">删除</button></td>
                        </tr>`
        $('#tbo').append(htmlTr)

        $('.jia').unbind('click')
        $('.jia').click(function () {
          var num = $(this).next().html()
          $(this)
            .next()
            .html(+num + 1)
          var goodsName = $(this).attr('name')
          var stock = $(`#tbod td:contains("${goodsName}")`).next().next()
          if ($(goods[2]).html() == 0) {
            alert(`${goodsName}已售尽`)
            return
          } else {
            stock.html(stock.html() - 1)
          }
          var price = $(this).parent().prev().html()
          $(this)
            .parent()
            .next()
            .html((+num + 1) * price)
        })

        $('.jian').unbind('click')
        $('.jian').click(function () {
          var num = $(this).prev().html()
          $(this)
            .prev()
            .html(+num - 1)
          var goodsName = $(this).attr('name')
          var stock = $(`#tbod td:contains("${goodsName}")`).next().next()
          stock.html(+stock.html() + 1)
          var price = $(this).parent().prev().html()
          $(this)
            .parent()
            .next()
            .html((+num - 1) * price)
          if (num == 1) {
            $(this).parent().parent().remove()
            return
          }
        })

        $('button:contains("删除")').unbind('click')
        $('button:contains("删除")').bind('click', function () {
          var num = $(this).parent().siblings().eq(2).children('span').html()
          var goodsName = $(this).parent().siblings().eq(0).html()
          var stock = $(`#tbod td:contains("${goodsName}")`).next().next()
          stock.html(+stock.html() + +num)
          $(this).parent().parent().remove()
        })
      }
    }

    function render() {
      var data = JSON.parse(localStorage.getItem('list'))
      if (data && data.length > 0) {
        var str = ''
        for (let i in data) {
          str += `
                        <tr>
                            <td>${data[i].商品名称}</td>
                            <td>${data[i].商品价格}</td>
                            <td>${data[i].库存}</td>
                            <td>${data[i].时间}</td>
                            <td>
                                <button onclick="delet()">删除</button>
                                <button onclick="bian(${i})" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">编辑</button>
                                <button onclick="gou(this)">加入购物车</button>
                            </td>
                        </tr>
                       `
          $('#tbod').html('')
          $('#tbod').append(str)
        }
      }
    }

    function bian(index) {
      var data = JSON.parse(localStorage.getItem('list'))
      $('input').eq(0).val(data[index].商品名称)
      $('input').eq(1).val(data[index].商品价格)
      $('input').eq(2).val(data[index].库存)
    }
    function setLocal(obj) {
      //判断数据
      if (!localStorage.getItem('list')) {
        //首次没有任何值 或者值为空的时候
        localStorage.setItem('list', JSON.stringify([obj]))
      } else {
        //已经有数据的时候 需要先获取数据
        let data = JSON.parse(localStorage.getItem('list'))
        //添加
        data.unshift(obj)
        //添加完数据之后再存入本地存储
        localStorage.setItem('list', JSON.stringify(data))
      }
    }

    function getNowTime() {
      return new Date().toLocaleString().replaceAll('/', '-')
    }

    function del(index) {
      //先获取数据
      let data = JSON.parse(localStorage.getItem('list'))
      //截取数组 （下标和长度）
      data.splice(index, 1)
      //重新设置本地数据
      localStorage.setItem('list', JSON.stringify(data))
    }
  </script>
</html>
